#include "usart.h"
#include "stm32f10x.h"
#include "uart_fifo.h"

#if 1
#pragma import(__use_no_semihosting)

struct __FILE
{
    int handle;

};

FILE __stdout;
_sys_exit(int x)
{
    x = x;
}
//
int fputc(int ch, FILE *f)
{
    while((USART1->SR&0X40)==0);
    USART1->DR = (u8) ch;
    return ch;
}
#endif


void uart_init(uint32_t bound)
{

    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
    //USART1_TX   PA.9
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    //USART1_RX	  PA.10
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);



    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);



    USART_InitStructure.USART_BaudRate = bound;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

    USART_Init(USART1, &USART_InitStructure);
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

    USART_Cmd(USART1, ENABLE);

}

void USART1_IRQHandler(void)                	//串口1中断服务程序
{
    u8 Res;

    if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)  //接收中断
    {
        Res =USART_ReceiveData(USART1);//(USART1->DR);
        uart_put_rx_chn(UART_CHN0,&Res,1);
        uart_rx_overtime_set(UART_CHN0,UART_RX_OVERTINME);
    }
    else if(USART_GetITStatus(USART1, USART_IT_TC) != RESET)//发送中断
    {
        if(uart_get_tx_chn(UART_CHN0,&Res,1))
        {
            USART_SendData(USART1,Res);
        }
        else
        {
            USART_ITConfig(USART1, USART_IT_TC, DISABLE);//发送完成  关闭发送
        }

    }

}

//串口1同步发送   会阻塞CPU
void uart1_send_data(uint8_t data[],uint16_t len)
{
    uint16_t i=0;
    for(i=0; i<len; i++)
    {
        USART_SendData(USART1,(uint16_t)data[i]);
        while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//等待发送完成
    }

}

//串口1异步发送  几乎不阻塞CPU
void uart1_write(uint8_t data[],uint16_t len)
{
    uart_put_tx_chn(0,data,len);
    USART_ITConfig(USART1, USART_IT_TC, ENABLE);//
}
